package com.sunb2b.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sunb2b.entity.Category;
import com.sunb2b.entity.CategoryAttr;
import com.sunb2b.service.CategoryService;
import com.sunb2b.service.Staticizer;
import com.sunb2b.util.IDUtils;

import freemarker.template.TemplateException;


@Controller
public class CategoryController {
    
    @Inject
    private CategoryService categoryService;
    
    @RequestMapping(value="/categoryUtil", method=RequestMethod.GET)
    public String categoryUtil(Model model){
        List<Category> categories = categoryService.getAllCategories();
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        for(int i=0; i<categories.size(); i++){
        	Category r = (Category)categories.get(i);
        	sb.append("'").append(r.getId()).append("':").append(r.toJsonString());
        	if(i!=categories.size()-1){
        		sb.append(",");
        	}
        }
        sb.append("}");
        System.out.println(sb.toString());
        model.addAttribute("categoriesJson", sb.toString());
        return "CategoryUtil";
    }
    
    public void staticize(Staticizer staticizer, String currentPath) 
    		throws IOException, TemplateException{
        List<Category> categories = categoryService.getAllCategories();
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        for(int i=0; i<categories.size(); i++){
        	Category r = (Category)categories.get(i);
        	sb.append("'").append(r.getId()).append("':").append(r.toJsonString());
        	if(i!=categories.size()-1){
        		sb.append(",");
        	}
        }
        sb.append("}");
        Map data = new HashMap();
        data.put("categoriesJson", sb.toString());
        Map env = new HashMap();
        env.put("data", data);
        env.put("tpl", "categoryUtil.ftl");
        env.put("outputFileName", currentPath + "/resources/scripts/categoryUtil.js");
        staticizer.process(env);
    }
    
    @RequestMapping(value="/admin/category/preStaticize")
    public String preStaticize(){
    	return "/admin/category/staticize";
    }
    
    @RequestMapping(value="/admin/category/staticize")
    public String staticize(HttpServletRequest request, Model model) 
    			throws IOException, TemplateException{
    	String currentPath = request.getSession().getServletContext().getRealPath("/");
        Staticizer staticizer = new Staticizer(currentPath + "/tpl");
        staticize(staticizer, currentPath);
        String message = "Operation was done successfully.";
        model.addAttribute("message", message);
    	return "/admin/category/staticize";
    }
    
    
    @RequestMapping(value="/admin/category/list", method=RequestMethod.GET)
    public String list(@RequestParam String id, Model model){
        //List categories = categoryService.getSubCategories(id);
        //Category parent = categoryService.getCategory(id);
        //model.addAttribute("categories", categories);
        model.addAttribute("parentId", id);
        
        return null;
    }
    
    @RequestMapping(value="/admin/category/update", method=RequestMethod.GET)
    public String preUpdate(WebRequest request, Model model){
        Category category; 
        String id = request.getParameter("id");
        if("".equals(id)||id==null){
            // add category
            category = new Category();
            String pid = request.getParameter("pid");
            category.setParentId(pid);
        }
        else{
            // update category
            category = categoryService.getCategory(id);
        }
        
        model.addAttribute("category", category);
        return "admin/category/update";
    }
    
    @RequestMapping(value="/admin/category/update", method=RequestMethod.POST)
    public String update(HttpServletRequest request, 
    		@Valid Category category, 
    		BindingResult result, 
    		Model model, 
    		RedirectAttributes redirectAttrs) throws IOException, TemplateException{
    	
    	if (result.hasErrors()) {
            return null;
        }
        if(category.getId()==null || "".equals(category.getId())){
            String id = categoryService.getMaxSubId(category.getParentId());
            id = IDUtils.getNextId(id);
            category.setId(id);
        }
        categoryService.save(category);
        String message = "表单提交成功.";
        model.addAttribute("message", message);
        redirectAttrs.addFlashAttribute("message", message);
        String currentPath = request.getSession().getServletContext().getRealPath("/");
        Staticizer staticizer = new Staticizer(currentPath + "/tpl");
        staticize(staticizer, currentPath);
        return "admin/category/update";
    }
    
    @RequestMapping(value="/admin/category/delete", method=RequestMethod.GET)
    public String delete(@RequestParam String ids, 
    			HttpServletRequest request, 
    			Model model, 
    			RedirectAttributes redirectAttrs) throws IOException, TemplateException{
        String [] _ids = ids.split(";");
        String id = _ids[0].substring(0, _ids[0].length()-3);
        try{
        	categoryService.delete(_ids);
        	redirectAttrs.addFlashAttribute("message", "操作成功");
        	String currentPath = request.getSession().getServletContext().getRealPath("/");
            Staticizer staticizer = new Staticizer(currentPath + "/tpl");
            staticize(staticizer, currentPath);
        }
        catch(DataIntegrityViolationException ex){
        	redirectAttrs.addFlashAttribute("message", "操作失败，请先删除所有该类别的产品。");
        }
        
        
        return "redirect:list?id=" + id;
    }
    
    @RequestMapping(value="/admin/category/attrList", method=RequestMethod.GET)
    public String attrList(@RequestParam String id, Model model){
    	Category category = categoryService.getCategory(id);
    	model.addAttribute("category", category);
        return null;
    }
    
    @RequestMapping(value="/admin/category/addAttr", method=RequestMethod.POST)
    public String addAttr(@RequestParam String newAttr, @RequestParam String categoryId, Model model){
    	CategoryAttr ca =  new CategoryAttr();
    	ca.setAttrName(newAttr);
    	Category category = categoryService.getCategory(categoryId);
    	ca.setCategory(category);
    	categoryService.addAttr(ca);
    	return "redirect:attrList?id=" + categoryId;
    }
    
    @RequestMapping(value="/admin/category/deleteAttr", method=RequestMethod.GET)
    public String deleteAttr(@RequestParam int id){
    	CategoryAttr ca = categoryService.getAttrById(id);
    	String categoryId = ca.getCategory().getId();
    	try{
    		categoryService.deleteAttr(ca);
    	}
    	catch(Exception ex){
    		
    	}
    	//redirectAttrs.addFlashAttribute("message", "删除成功!");
        return "redirect:attrList?id=" + categoryId;
    }
    
    
}

